package com.util;

import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

/**
 * LucenceConvert 配置工具类
 *
 * @author hutongfu
 * @since 2018-01-08 10:10
 */
public class LucenceConfig {
    /**
     * 索引目录
     */
    private static Directory directory;

    /**
     * 分词器
     */
    private static IKAnalyzer analyzer;

    /**
     * 写索引的配置
     */
    private static IndexWriterConfig indexWriterConfig;

    /**
     * 索引目录
     */
    private static String indexPath = "E:\\maven_workspace\\lucence\\writer";

    public static Directory getDirectory() {
        return directory;
    }

    public static IKAnalyzer getIkAnalyzer() {
        return analyzer;
    }

    public static IndexWriterConfig getIndexWriterConfig() {
        return indexWriterConfig;
    }

    static {
        try { //文件目录
            directory = FSDirectory.open(new File(indexPath));
            //创建分词器
            analyzer = new IKAnalyzer();
            indexWriterConfig = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);

            //指定在JVM退出前要执行的代码
            Runtime.getRuntime().addShutdownHook(new Thread() {

                @Override
                public void run() {
                    LucenceUtil.indexChanged();
                    try {
                        if (null != directory) {
                            directory.close();
                        }
                    } catch (IOException e) {
                        System.out.println("关闭索引目录错误......");
                        throw new RuntimeException(e);
                    }
                }
            });

        } catch (IOException e) {
            System.out.println("LucenceConvert 配置错误......");
            throw new RuntimeException(e);
        }

    }

}
